package com.nh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nh.commom.util.PageResult;
import com.nh.entity.Library;
import com.nh.entity.Books;
import com.nh.mapper.BooksMapper;
import com.nh.service.ILibraryService;
import com.nh.service.IBooksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nh.VO.BooksVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author QAQ
 * @since 2025-01-13
 */
@Service
public class BooksServiceImpl extends ServiceImpl<BooksMapper, Books> implements IBooksService {
    @Autowired
    private ILibraryService libraryService;

    @Override
    public PageResult<Books> findByPage(Integer page, Integer pageSize) {
        QueryWrapper<Books> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0);
        Page<Books> page1 = this.page(new Page<>(page, pageSize), wrapper);
        return new PageResult<>(page1.getRecords(), page1.getTotal());
    }

    @Override
    public PageResult<Books> search(Integer page, Integer pageSize, BooksVO vo) {
        QueryWrapper<Books> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0);
        wrapper.like(StrUtil.isNotBlank(vo.getBname()), "bname", vo.getBname());
        wrapper.like(StrUtil.isNotBlank(vo.getAuthor()), "author", vo.getAuthor());
        wrapper.eq(vo.getLid() != null && vo.getLid() != 0, "lid", vo.getLid());
        Page<Books> page1 = this.page(new Page<>(page, pageSize), wrapper);
        page1.getRecords().forEach(book -> {
            Library library = libraryService.getById(book.getLid());
            book.setLname(library.getLname());
        });
        return new PageResult<>(page1.getRecords(), page1.getTotal());
    }

    @Override
    public boolean add(Books book) {
        return this.save(book);
    }

    @Override
    public boolean deleteById(Integer bid) {
        Books book = this.getById(bid);
        if (book == null) {
            return false;
        }
        book.setDeleted(1);
        return this.updateById(book);
    }
}
